#include "../http/recv_request_aw.h"
#include "../http/parser.h"
#include <cstddef>

namespace wilson::http
{
    bool 
    recv_request_aw::
    await_ready() 
    {
        return net::recv_aw::await_ready();
    }

    void 
    recv_request_aw::
    await_suspend(::std::coroutine_handle<> h)
    {
        net::recv_aw::await_suspend(h);
    }

    server::request 
    recv_request_aw::
    await_resume()
    {
        server::request_parser parser{ m_storage };

        /* Check whether there is a networking error
         * (usually the peer socket has been shutdown/close) 
         * or not.
         *
         * The `basic_request` has NO default ctor.
         * But parser can generate an empty request object.
         */
        if (m_ec_ptr && *m_ec_ptr) return parser.generate();

        size_t nread = net::recv_aw::await_resume();
        auto buffer = m_storage->get_writeable_block(0);
        if (nread < buffer.size())
            buffer[nread] = ::std::byte{0};
        auto err = parser.execute();
        if (m_ec_ptr) *m_ec_ptr = err;

        return parser.generate();
    }
}
